#include <Wire.h>
#include <Adafruit_INA219.h>
#include <Adafruit_BMP085.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <hp_BH1750.h>

#define DHTPIN 2
#define DHTTYPE DHT22

Adafruit_INA219 ina;
Adafruit_BMP085 bmp;
DHT_Unified dht(DHTPIN, DHTTYPE);
hp_BH1750 bh;

int ledPin = 13;
bool ledState;

int interval = 2000;  //ms
unsigned long lastTick = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  while (!Serial) {
    delay(1);
  }
  if (!ina.begin()) {
    Serial.println("Failed to find INA219 chip");
    while (1) { delay(10); }
  }
  //default is 32V 2A
  //ina219.setCalibration_32V_1A();
  ina.setCalibration_16V_400mA();

  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }

  dht.begin();

  //BH1750::CONTINUOUS_HIGH_RES_MODE
  //BH1750::CONTINUOUS_HIGH_RES_MODE_2
  //Wire.begin();
  //if (!bh.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
  //  Serial.println(F("Error initialising BH1750"));
  //  while (1) {}
  //}

  bh.begin(BH1750_TO_GROUND);
  bh.calibrateTiming();
  bh.start();

  lastTick = millis();
}

void loop(void) {
  while (millis() - lastTick < interval) {
    return;
  }
  lastTick = millis();
  digitalWrite(ledPin, !ledState);
  //ina
  float shuntvoltage = ina.getShuntVoltage_mV();
  float busvoltage = ina.getBusVoltage_V();
  float current_mA = ina.getCurrent_mA();
  //float power_mW = ina.getPower_mW();
  float loadvoltage = busvoltage + (shuntvoltage / 1000);
  //bmp
  float presure_bmp = bmp.readPressure();
  float temperature_bmp = bmp.readTemperature();
  //DHT
  sensors_event_t event;
  float tempture_dht = 0;
  float humidity_dht = 0;
  dht.temperature().getEvent(&event);
  if (isnan(event.temperature)) {
    Serial.println("Error reading temperature!");
    return;
  }
  tempture_dht = event.temperature;
  dht.humidity().getEvent(&event);
  if (isnan(event.relative_humidity)) {
    Serial.println("Error reading humidity!");
    return;
  }
  humidity_dht = event.relative_humidity;
  //BH
  float lux = 0;
  //if (bh.measurementReady(true))
  //  lux = bh.readLightLevel();
  if (bh.hasValue()) {
    lux = bh.getLux();
    bh.start();
  }

  //Sendout
  Serial.print(lux);
  Serial.print(',');
  Serial.print(presure_bmp);
  Serial.print(',');
  Serial.print(humidity_dht);
  Serial.print(',');
  Serial.print(tempture_dht);
  Serial.print(',');
  Serial.print(loadvoltage * 261.51);
  Serial.print(',');
  Serial.println(current_mA / 95.5 * 80);
}
